package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import javax.inject.{Inject, Singleton}
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by yz on 2018/7/17
 */
@Singleton
class BioSampleDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import utils.MyPostgresProfile.api._
  import com.github.tototoshi.slick.MySQLJodaSupport._

  type MyRow = BioSampleRow
  val table = BioSample

  def insertAll(rows: List[MyRow]) = db.run(table ++= rows).map(_ => ())

  def deleteAll = db.run(table.delete).map(_ => ())

  def selectAll = db.run(table.result)

  def selectAllLocation = db.run(table.map { x =>
    x.attributes.+>>("geographic location").?
  }.filter(_.isDefined).map(_.get).result)

  def selectAllIdLocation = db.run(table.map { x =>
    (x.bioSample, x.attributes.+>>("geographic location").?)
  }.filter { case (id, locationOp) =>
    locationOp.isDefined
  }.map { case (id, locationOp) =>
    (id, locationOp.get)
  }.result)

  def selectAll(country: String) = db.run(table.filter { x =>
    x.attributes.+>>("geographic location").startsWith(country)
  }.map(_.bioSample).result)

  def select(id: String) = db.run(table.filter(_.bioSample === id).result.head)


}
